from tortoise import fields, models
from passlib.context import CryptContext

from models.address import Address

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") 

class User(models.Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=50, unique=True,description="用户名")
    password = fields.CharField(max_length=128,description="密码")
    email = fields.CharField(max_length=50, unique=True,description="邮箱",default=None, null=True)
    phone = fields.CharField(max_length=20, unique=True,description="手机号",default=None, null=True)
    user_type= fields.CharField(max_length=10,default='普通用户',description="用户类型",choices=[('普通用户','普通用户'),('分销员', '分销员')])
    login_type = fields.CharField(max_length=10, default='本地', description="登录类型", choices=[('本地', '本地'), ('支付宝', '支付宝'), ('微信', '微信')])
    third_party_id = fields.CharField(max_length=100, default=None, null=True, description="第三方ID")
    third_party_account = fields.CharField(max_length=100, default=None, null=True, description="第三方账号")
    third_party_phone = fields.CharField(max_length=20, default=None, null=True, description="第三方手机号")
    create_time = fields.DatetimeField(auto_now_add=True,description="创建时间")
    update_time = fields.DatetimeField(auto_now=True,description="更新时间")
    avatar = fields.CharField(max_length=255, null=True, default=None, description="用户头像URL")
    membership_level = fields.ForeignKeyField("models.MembershipLevel", related_name="users", null=True, on_delete=fields.SET_NULL, description="会员等级")
    balance = fields.DecimalField(max_digits=12, decimal_places=2, description="余额")
    # 关联收货地址（一对多）：一个用户可对应多个地址
    addresses = fields.ReverseRelation["Address"]  # 关联 Address 模型的外键（需在 Address 中定义外键）
    
    class Meta:
        table = "user"

    def verify_password(self, plain_password):
        return pwd_context.verify(plain_password, self.password)

    def set_password(self, password:str):
        self.password = pwd_context.hash(password)

    

class MembershipLevel(models.Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=10, description="会员等级名称",choices=[('普通', '普通'), ('白银', '白银'), ('黄金', '黄金'), ('钻石', '钻石')])
    upgrade_amount = fields.DecimalField(max_digits=10, decimal_places=2, default=0.00, description="升级金额")
    level = fields.IntField(description="等级数值")
    created_at = fields.DatetimeField(auto_now_add=True, description="创建时间")

    class Meta:
        table = "membership_level"
        